//
//  NewPostViewController.m
//  Buzz API Demo
//
//  Created by Peter Hopkins on 5/12/10.
//  Copyright 2010 Google Inc. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "NewPostViewController.h"

#import "BuzzDao.h"
#import "Post.h"

@interface NewPostViewController ()
- (void)postedByDao:(BuzzDao *)dao error:(NSError *)error;
@end

@implementation NewPostViewController

@synthesize postTextView = postTextView_;
@synthesize postToolbar = postToolbar_;
@synthesize navigationItem = navigationItem_;

- (id)initWithDao:(BuzzDao *)dao {
  return [self initWithDao:dao commentingOnPost:nil];
}

- (id)initWithDao:(BuzzDao *)dao commentingOnPost:(Post *)post {
  if ((self = [super initWithNibName:nil bundle:nil])) {
    dao_ = [dao retain];
    post_ = [post retain];
  }

  return self;
}


- (void)viewDidLoad {
  if (post_) {
    [navigationItem_ setTitle:@"New Comment"];

    CGRect textFrame = [postTextView_ frame];
    textFrame.size.height += 44;
    [postTextView_ setFrame:textFrame];

    [postToolbar_ setHidden:YES];
  } else {
    [navigationItem_ setTitle:@"New Buzz"];
  }
}


- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];

  [postTextView_ becomeFirstResponder];
}


- (void)viewDidUnload {
  [self setPostTextView:nil];
}


#pragma mark Actions

- (IBAction)cancelBuzz:(id)sender {
  [postTextView_ resignFirstResponder];
  [self dismissModalViewControllerAnimated:YES];
}


- (IBAction)postBuzz:(id)sender {
  [sender setEnabled:NO];

  if (post_ == nil) {
    Post *post = [[dao_ newPost] autorelease];
    [post setContentHTML:[postTextView_ text]];

    [dao_ post:post delegate:self selector:@selector(postedByDao:error:)];
  } else {
    Comment *comment = [[dao_ newComment] autorelease];
    [comment setContentHTML:[postTextView_ text]];

    [dao_ comment:comment onPost:post_ delegate:self selector:@selector(postedByDao:error:)];
  }
}


#pragma mark Callback

- (void)postedByDao:(BuzzDao *)dao error:(NSError *)error {
  if (!error) {
    [postTextView_ resignFirstResponder];
    [self dismissModalViewControllerAnimated:YES];
  }
}


#pragma mark Memory management

- (void)dealloc {
  [navigationItem_ release];
  [postTextView_ release];
  [postToolbar_ release];
  [dao_ release];
  [post_ release];

  [super dealloc];
}


@end
